<?php

namespace app\macht\controller;

use app\common\controller\Platurl;
use app\common\model\Agent;
use app\common\model\CardBirthdayCare;
use app\common\model\CardClickReplyPut;
use app\common\model\CardClickReplyPutlog;
use app\common\model\CardCzgive;
use app\common\model\CardFans;
use app\common\model\CardFansGroupDict;
use app\common\model\CardFansNotice;
use app\common\model\CardFollowcard;
use app\common\model\CardFollowcardlog;
use app\common\model\CardFreecard;
use app\common\model\CardFreecardlog;
use app\common\model\CardGamcash;
use app\common\model\CardGeneral;
use app\common\model\CardGive;
use app\common\model\CardLeaduserLins;
use app\common\model\CardMember;
use app\common\model\CardPaycard;
use app\common\model\CardPaycardlog;
use app\common\model\CardPutRule;
use app\common\model\CardPutRuleMass;
use app\common\model\CardRank;
use app\common\model\CardShareLog;
use app\common\model\CardShareRule;
use app\common\model\CardShareUser;
use app\common\model\CardUserBonus;
use app\common\model\CardUserFee;
use app\common\model\CardUserGet;
use app\common\model\CardUserGetAli;
use app\common\model\CardUserUpdate;
use app\common\model\CardUserUpdateAli;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\OpenTemplate;
use app\common\model\PaymentCardPut;
use app\common\model\System;
use app\common\model\WxOpen;
use app\common\model\CardLeaduser;
use app\common\controller\Excel;
use app\common\controller\AdminBase;
use app\merchant\job\Start;
use think\Config;
use think\Controller;
use think\Debug;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Marke extends MachBase
{
    //首页
    public function index()
    {
        return $this->fetch();
    }

    //活动工具
    public function tools()
    {
        return $this->fetch();
    }

    public function excel()
    {
        $request = request();
        if ($request->isAjax()) {
            try {
                $arr = $request->post();
                $mid = $arr['mid'];
                $top_mid = Session::get('login_top_mid');
                $title = array("name", "sex", "address", "birthday", "old_code", "phone", "bonus", "balance", "statu", "creattime");
                $file = ROOT_PATH . 'public' . $arr['excel'];
                $data = $this->loads($file, $title);
                if (count($data) <= 500) {
                    foreach ($data as $k => $v) {
                        $data[$k]['creattime'] = strtotime($v['creattime']);
                        $data[$k]['birthday'] = strtotime($v['birthday']);
                        $data[$k]['top_mid'] = $top_mid;
                        $data[$k]['mid'] = $mid;
                    }
                    $CardLeaduser = new CardLeaduser();
                    $add = $CardLeaduser->allowField(true)->saveAll($data);
                    if ($add) {
                        $datas = array('code' => 0, 'message' => '添加成功');
                    } else {
                        $datas = array('code' => 9001, 'message' => $CardLeaduser->getError());
                    }
                } else {
                    $datas = array('code' => 9002, 'message' => '单次导入超过500人');
                }
            } catch (\Exception $e) {
                $datas = array('code' => 2, 'message' => $e->getMessage());
            }
            return json($datas);
        }
    }


    //支付即会员
    public function paycard()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        if (Request()->isPost()) {
            $cardtype = $this->gettype($card_id);
            $arr = request()->post();
            $times = explode(" - ", $arr['times']);
            $begintime = $times[0];
            $endtime = $times[1];
            $data = [
                "rule_info" => [
                    "type" => "RULE_TYPE_PAY_MEMBER_CARD",
                    "base_info" => [
                        "mchid_list" => [        //支付商户号
                            explode(',', $arr['mchid_list'])
                        ],
                        "begin_time" => strtotime($begintime),      //开始时间
                        "end_time" => strtotime($endtime)         //结束时间
                    ],
                    "member_rule" => [
                        "card_id" => $card_id,          //card_id
                        "least_cost" => $arr['lcost'] * 100,               //金额下限 (以分为单位)
                        "max_cost" => $arr['mcost'] * 100,             //金额上限 (以分为单位)
                    ]
                ]
            ];

            $options = $this->options();
            $weObj = new Wxobjopen($options);
            $res = $weObj->payPut($data);

            if ($res['errcode'] == 0 && $res['errmsg'] == 'ok') {
                if (!$res['fail_mchid_list']) {

                    $adata = [
                        'card_id' => $card_id,
                        'top_mid' => Session::get('login_top_mid'),
                        'rule_type' => 'pay_card',
                        'sub_mach_id' => $arr['mchid_list'],
                        'rule_id' => $res['rule_id'],
                        'card_type' => $cardtype,
                        'begin_time' => strtotime($begintime),
                        'end_time' => strtotime($endtime),
                        'least_cost' => $arr['lcost'],
                        'max_cost' => $arr['mcost'],
                        'statu' => 0,
                        'creattime' => time(),
                    ];
                    $cardput = new CardPutRule();
                    $cardput->allowField(true)->save($adata);

                    $this->success('设置成功！', url('marke/paycard', ['card_id' => $card_id]), '', 30);
                } else {
                    $errcode = "";
                    $errmesg = "";
                    foreach ($res['fail_mchid_list'] as $k => $v) {
                        $errcode .= $v['errcode'];
                        $errmesg .= 'errcode:' . $errcode . 'errmsg' . $v['errmsg'];
                    }
                    $this->error($errcode . $errmesg, url('marke/paycard', ['card_id' => $card_id]), '', 30);

                }
            } else {
                $errmesg = 'errcode:' . $res['errcode'] . 'errmsg' . $res['errmsg'];
                $this->error($res['errcode'] . $errmesg, url('marke/paycard', ['card_id' => $card_id]), '', 30);
            }
        } else {
            $mid = $this->get_mer_mid();
            $CardPutRule = new CardPutRule();
            $map['top_mid'] = Session::get('login_top_mid');
            $rutlist = $CardPutRule->where($map)->select();
            if ($rutlist) {
                $card['pay_type'] = 1;
            } else {
                $card['pay_type'] = 2;
            }
            $card['card_id'] = $card_id;
            $this->assign('rutlist', $rutlist);
            $this->assign('card', $card);
            return $this->fetch();
        }
    }

    //查询支付即会员
    public function getpaycard()
    {
        $data = [
            "type" => "RULE_TYPE_PAY_MEMBER_CARD",
            "effective" => true,
            "offset" => 0,
            "count" => 49
        ];
        $open = $this->options();
        $wxObj = new Wxobjopen($open);
        $res = $wxObj->payPutGetList($data);
        dump($res);
    }

    //删除支付即会员
    public function payputdel()
    {
        $cardput = new CardPutRule();
        $arr = request()->param();
        if (isset($arr['rule_id'])) {
            $data = [
                'rule_id' => $arr['rule_id'],
            ];
            $options = $this->options();
            $weObj = new Wxobjopen($options);
            $res = $weObj->payputdel($data);
            if ($res['errcode'] == 0) {

                $cardput->where('id', $arr['id'])->delete();
                $this->success('删除成功', url('marke/paycard', ['card_id' => $arr['card_id']]));
            } else {
                $this->error('删除失败', url('marke/paycard', ['card_id' => $arr['card_id']]));
            }
        }else{
            $res = $cardput->where('id', $arr['id'])->delete();
            if($res){
                $this->success('删除成功', url('marke/paycard', ['card_id' => $arr['card_id']]));
            } else {
                $this->error('删除失败', url('marke/paycard', ['card_id' => $arr['card_id']]));
            }
        }
    }

    //分享设置
    public function setshare($card_id='')
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        $CardShareRule = new CardShareRule();
        $info = $CardShareRule->where('card_id', $card_id)->find();
        if (Request()->isAjax()) {
            $arr = request()->post();
            $data = $arr;
            $data['card_type'] = 'MEMBER_CARD';
            $data['rule_type'] = 'SHARE';
            $data['create_time'] = time();
            if (isset($arr['is_account'])){
                $data['is_account'] = $arr['is_account'];
            }
            if ($data['is_cards'] == "Y") {
                $cardlist = $this->card_zs_list($param['cardlist']);
                $data['zs_no'] = count($cardlist);
                $data['zs_card_id_all'] = json_encode($cardlist, JSON_UNESCAPED_UNICODE);
                $data['zs_card_info'] = getgivecardnewnoz($data['zs_card_id_all'], 0);
            }else{
                $data['zs_no'] = 0;
                $data['zs_card_id_all'] = "";
                $data['zs_card_info'] = "";
            }
            //END
            //修改

            if ($info) {
                $res = $CardShareRule->allowField(true)->save($data, ['card_id' => $card_id]);
            } else {
                //保存
                unset($data['id']);
                $data['card_id'] = $card_id;
                $res = $CardShareRule->allowField(true)->save($data);
            }
            if ($res){
                $resa = ['code'=>0,'message'=>'success'];
            }else{
                $resa = ['code'=>9001,'message'=>'error'];
            }
            return json($resa);
        } else {
            $card['card_id'] = $card_id;
            $list = $CardShareRule->where('card_id', $card_id)->select();
            if ($list) {
                $Platurl = new Platurl();
                $agent_url = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
                $rule_id = $CardShareRule->where('card_id', $card_id)->value('id');
                $card['sharelink'] = $agent_url . '/mobile.php/cardmarke/cardshare/rule_id/' . $rule_id . '/card_id/' . $card_id;
            } else {
                $card['sharelink'] = '';
            }
            $this->assign('list', $list);
            $this->assign('card', $card);
            $this->assign('info', $info);
            return $this->fetch();
        }
    }

    public function getsharecardslist(Request $request){
        if ($request->isAjax()) {
            $param = $request->post();
            $CardGen = new CardGeneral();
            $CardShareRule = new CardShareRule();
            $info = $CardShareRule->where(array('id' => $param['id']))->find();
            $zs_card_id_all = json_decode($info['zs_card_id_all'], true);
            $cardlist = [];
            foreach ($zs_card_id_all as $k=>$v){
                $cardinfo = $CardGen->where('card_id',$v['zs_card_id'])->field('get_limit,title')->find();
                $cardlist[$k]['title'] = $cardinfo['title'];
                $cardlist[$k]['card_id'] = $v['zs_card_id'];
                $cardlist[$k]['get_limit'] = $cardinfo['get_limit'];
                $cardlist[$k]['zs_no'] = $v['zs_no'];
            }
            return json($cardlist);
        }
    }


    //分享设置删除
    public function delshare()
    {
        if (Request()->isGet()) {
            $arr = request()->param();
            $CardShareRule = new CardShareRule();
            $res = $CardShareRule->where('id', $arr['id'])->delete();
            if ($res) {
                $CardShareUser = new CardShareUser();
                $del = $CardShareUser->where(['rule_id'=>$arr['id']])->delete();
                $this->success('删除成功', url('marke/setshare', ['card_id' => $arr['card_id']]));
            } else {
                $this->error('删除失败', url('marke/setshare', ['card_id' => $arr['card_id']]));
            }
        }
    }

    //分享设置状态
    public function statushare()
    {
        if (Request()->isGet()) {
            $arr = request()->param();
            $CardShareRule = new CardShareRule();
            $data['statu'] = $arr['statu'] == 1 ? 0 : 1;
            $res = $CardShareRule->save($data, ['id' => $arr['id']]);
            if ($res) {
                $this->success('设置成功', url('marke/setshare', ['card_id' => $arr['card_id']]));
            } else {
                $this->error('设置失败', url('marke/setshare', ['card_id' => $arr['card_id']]));
            }
        }
    }

    //分享统计
    public function sharecount()
    {
        $arr = request()->param();
        if (!isset($arr['id']) && !isset($arr['card_id'])) {
            $CardMermber = new CardMember();
            $CardShareRule = new CardShareRule();
            $arr['card_id'] = $CardMermber->where(['top_mid' => Session::get('login_top_mid')])->value('card_id');
            $arr['id'] = $CardShareRule->where('card_id', $arr['card_id'])->value('id');
        }
        $CardShareUser = new CardShareUser();
        $map['rule_id'] = $arr['id'];
        $map['card_id'] = $arr['card_id'];
        $p_data = request()->get();
        unset($p_data['page']);
        if ($p_data) {
            //卡号
            if ($p_data['code'] != '') {
                $map['code'] = array('like', '%' . trim($p_data['code']) . '%');
            }
            //时间
            if (!empty($p_data['search_date'])) {
                $date = explode(" - ", $p_data['search_date']);
                $starttime = strtotime($date[0]);
                $endtime = strtotime($date[1]);
            } else {
                $starttime = strtotime("last month") - 86400;
                $endtime = time();
            }
            $map['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
        } else {
            $p_data['code'] = '';
        }
        $list = [];
        $CardUserFee = new CardUserFee();
        $CardUserGet = new CardUserGet();
        $list = $CardShareUser->where($map)->order('get_ren', 'desc')->paginate('10', false, ['query' => request()->param()]);      //列表
        $info['share_ren'] = $CardShareUser->where($map)->count('id');          //分享人数
        //开卡人数
        $info['open_ren'] =  $CardShareUser->where($map)->sum('get_ren');          //领卡人数
        //END
        //激活人数
        $info['fire_ren'] =  $CardShareUser->where($map)->sum('fire_ren');          //激活人数
        //END
        //充值笔数
        $outerstr = $CardShareUser->where($map)->field('outerstr')->select();   //渠道查询
        $outerst = [];
        foreach ($outerstr as $k=>$v){
            $outerst[] = $v['outerstr'];
        }
        $mapsa['outerstr'] = ['in',$outerst];
        $mapsa['fire'] = 1;
        $user = $CardUserGet->where($mapsa)->field('code')->select();
        $code = [];
        foreach ($user as $ks=>$vs){
            $code[] = $vs['code'];
        }
        $mapsu['code'] = ['in',$code];
        $mapsu['cate'] = 1;
        $mapsu['type'] = 1;
        $info['reg_num'] = $CardUserFee->where($mapsu)->count('id');
        //END
        //充值金额
        $info['reg_price'] = $CardUserFee->where($mapsu)->sum('num');
        //END
        //消费金额
        $mapsux['code'] = ['in',$code];
        $mapsux['cate'] = 2;
        $mapsux['type'] = 2;
        $info['xf_price'] = $CardUserFee->where($mapsux)->sum('num');
        //END
//        $list = [];
        foreach ($list as $k=>$v){
            $maps['outerstr'] = $v['outerstr'];
            $getcode = $CardUserGet->where($maps)->column('code');    //领取人数据
            $mab['code'] = ['in', $getcode];
            $mab['cate'] = ['in',[1]];
            $list[$k]['cz_num'] = $CardUserFee->where($mab)->count('id');   //充值笔数
            $list[$k]['cz_price_num'] = $CardUserFee->where($mab)->sum('num');   //充值额
        }

        $this->assign('list', $list);
        $this->assign('info', $info);
        return $this->fetch();
//        }
    }

    //分享记录
    public function sharelog()
    {
        $arr = request()->param();
        if (isset($arr['outerstr'])) {
            $CardUserGet = new CardUserGet();
            $CardUserFee = new CardUserFee();
            $p_data = request()->get();
            unset($p_data['page']);
            if ($p_data) {
                //卡号
                if (!empty($p_data['code'])) {
                    $map['code'] = array('like', '%' . trim($p_data['code']) . '%');
                    $mab['code'] = array('like', '%' . trim($p_data['code']) . '%');
                }
                //激活
                if (!empty($p_data['fire'])) {
                    $map['fire'] = $p_data['fire'];
                }
                //时间
                if (!empty($p_data['search_date'])) {
                    $date = explode(" - ", $p_data['search_date']);
                    $starttime = strtotime($date[0]);
                    $endtime = strtotime($date[1]);
                    $map['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
                    $mab['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
                }
            } else {
                $p_data['code'] = '';
                $p_data['fire'] = '';
            }
            if (isset($arr['fire'])) {
                $map['fire'] = $arr['fire'];
            }
            $map['outerstr'] = $arr['outerstr'];
            $list = $CardUserGet->where($map)->paginate('10', false, ['query' => request()->param()]);      //领取人列表
            foreach ($list as $k=>$v){
                $mabs['code'] = $v['code'];
                $mabs['cate'] = 1;
                $list[$k]['cz_num'] = $CardUserFee->where($mabs)->count('id');   //充值笔数
                $list[$k]['cz_price_num'] = $CardUserFee->where($mabs)->sum('num');   //充值额
            }
            $getcode = $CardUserGet->where($map)->column('code');    //领取人数据
            //领取统计
            $getsum['getsum'] = $CardUserGet->where(['outerstr' => $arr['outerstr']])->count('id');                //领取
            $getsum['firesum'] = $CardUserGet->where(['outerstr' => $arr['outerstr'], 'fire' => 1])->count('id');               //激活
            $mab['code'] = ['in', $getcode];
            $mab['cate'] = ['in', [1]];
            $getsum['del_balsum'] = $CardUserFee->where($mab)->sum('num');   //消费额
            $mab['cate'] = 1;
            $getsum['add_balsum'] = $CardUserFee->where($mab)->sum('num');   //充值额
            $this->assign('getsum', $getsum);
            $this->assign('list', $list);
            return $this->fetch();
        }
    }

    //获取本会员余额变动详情
    public function shareuserbalance(){

        $param = request()->param();
        if (isset($param['get_id'])) {
            $CardUserGet = new CardUserGet();
            $CardUserFee = new CardUserFee();
            $p_data = request()->get();
            unset($p_data['page']);
            unset($p_data['card_id']);
            unset($p_data['get_id']);
            if ($p_data) {
                if (!empty($p_data['type'])) {
                    $map['type'] = $p_data['type'];
                }
                if (!empty($p_data['source'])) {
                    $map['source'] = $p_data['source'];
                }
                //时间
                if (!empty($p_data['search_date'])) {
                    $date = explode(" - ", $p_data['search_date']);
                    $starttime = strtotime($date[0]);
                    $endtime = strtotime($date[1]);
                    $map['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
                }

            } else {
                $p_data['type'] = ['in', ['1,2']];
                $p_data['starttime'] = '';
                $p_data['endtime'] = '';
                $p_data['source'] = '请选择';
            }
            $get_id = $param['get_id'];
            $arr = $CardUserGet->where('id', $get_id)->field('openid,card_id,code')->find();
            $map['openid'] = $arr['openid'];
            $map['card_id'] = $arr['card_id'];
            $map['code'] = $arr['code'];
            $list = $CardUserFee->where($map)->order('id desc')->paginate(15, false, ['query' => request()->param()]);
//        var_dump($CardUserUpdate->getLastSql());
            $this->assign('list', $list);
            $this->assign('p_data', $p_data);
            return $this->fetch();
        }
    }

    //分享设置
    public function setshareali($template_id)
    {
        $CardShareRule = new CardShareRule();
        $info = $CardShareRule->where('template_id', $template_id)->find();
        if (Request()->isPost()) {
            $arr = request()->post();
            $data = $arr;
            $data['card_type'] = 'MEMBER_CARD';
            $data['rule_type'] = 'SHARE';
            $data['create_time'] = time();
            //修改
            if ($info) {
                $res = $CardShareRule->allowField(true)->save($data, ['template_id' => $template_id]);
            } else {
                //保存
                $data['template_id'] = $template_id;
                $res = $CardShareRule->allowField(true)->save($data);
            }
            if ($res) {
                $this->success('设置成功', url('marke/setshare', ['template_id' => $template_id]));
            } else {
                $this->error('设置失败', url('marke/setshare', ['template_id' => $template_id]));
            }
        } else {
            $card['template_id'] = $template_id;
            $list = $CardShareRule->where('template_id', $template_id)->select();
            if ($list) {
                $Platurl = new Platurl();
                $agent_url = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
                $rule_id = $CardShareRule->where('template_id', $template_id)->value('id');
                $card['sharelink'] = $agent_url . '/mobile.php/cardmarke/cardshareali/rule_id/' . $rule_id . '/template_id/' . $template_id;
            } else {
                $card['sharelink'] = '';
            }
            $this->assign('list', $list);
            $this->assign('card', $card);
            $this->assign('info', $info);
            return $this->fetch();
        }
    }

    //分享设置删除
    public function delshareali()
    {
        if (Request()->isGet()) {
            $arr = request()->param();
            $CardShareRule = new CardShareRule();
            $res = $CardShareRule->where('id', $arr['id'])->delete();
            if ($res) {
                $this->success('删除成功', url('marke/setshareali', ['template_id' => $arr['template_id']]));
            } else {
                $this->error('删除失败', url('marke/setshareali', ['template_id' => $arr['template_id']]));
            }
        }
    }

    //分享设置状态
    public function statushareali()
    {
        if (Request()->isGet()) {
            $arr = request()->param();
            $CardShareRule = new CardShareRule();
            $data['statu'] = $arr['statu'] == 1 ? 0 : 1;
            $res = $CardShareRule->save($data, ['id' => $arr['id']]);
            if ($res) {
                $this->success('设置成功', url('marke/setshare', ['template_id' => $arr['template_id']]));
            } else {
                $this->error('设置失败', url('marke/setshare', ['template_id' => $arr['template_id']]));
            }
        }
    }

    //分享统计
    public function sharecountali()
    {
        $arr = request()->param();
        if (isset($arr['template_id'])) {
            $CardShareUser = new CardShareUser();
            $map['template_id'] = $arr['template_id'];
            $p_data = request()->get();
            unset($p_data['page']);
            if ($p_data) {
                //卡号
                if ($p_data['code'] != '') {
                    $map['code'] = array('like', '%' . trim($p_data['code']) . '%');
                }
                //时间
                if ($p_data['starttime'] !== '') {
                    $starttime = strtotime($p_data['starttime']);
                } else {
                    $starttime = 0;
                }
                if ($p_data['endtime'] !== '') {
                    $endtime = strtotime($p_data['endtime']) + 86400;
                } else {
                    $endtime = strtotime(date('Y-m-d H:i:s'));
                }
                $map['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
            } else {
                $p_data['code'] = '';
            }
            $list = $CardShareUser->where($map)->paginate('20', false, ['query' => request()->param()]);

            $this->assign('list', $list);
            return $this->fetch();
        }
    }

    //分享记录
    public function sharelogali()
    {
        $arr = request()->param();
        if (isset($arr['outerstr'])) {
            $CardUserGet = new CardUserGetAli();
            $CardUserUpdate = new CardUserUpdateAli();
            $p_data = request()->get();
            unset($p_data['page']);
            if ($p_data) {
                //卡号
                if ($p_data['code'] != '') {
                    $map['code'] = array('like', '%' . trim($p_data['code']) . '%');
                    $mab['code'] = array('like', '%' . trim($p_data['code']) . '%');
                }

                //时间
                if ($p_data['starttime'] !== '') {
                    $starttime = strtotime($p_data['starttime']);
                } else {
                    $starttime = 0;
                }
                if ($p_data['endtime'] !== '') {
                    $endtime = strtotime($p_data['endtime']) + 86400;
                } else {
                    $endtime = strtotime(date('Y-m-d H:i:s'));
                }
                $map['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
                $mab['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
            } else {
                $p_data['code'] = '';
                $p_data['fire'] = '';
            }

            $map['outerstr'] = $arr['outerstr'];
            $list = $CardUserGet->where($map)->paginate('20', false, ['query' => request()->param()]);      //领取人列表
            $getcode = $CardUserGet->where($map)->column('code');    //领取人数据
            //领取统计
            $mab['code'] = ['in', $getcode];
            $getsum['getsum'] = $CardUserGet->where(['user_id' => $arr['outerstr']])->count('id');                //领取
//            $getsum['firesum'] = $CardUserGet->where(['outerstr'=>$arr['outerstr'],'fire'=>1])->count('id');               //激活
            $getsum['del_balsum'] = $CardUserUpdate->where($mab)->sum('del_balance');   //消费额
            $getsum['add_balsum'] = $CardUserUpdate->where($mab)->sum('add_balance');   //充值额
            $this->assign('getsum', $getsum);
            $this->assign('list', $list);
            return $this->fetch();
        }
    }


    //激活送券
    public function firegive()
    {
        $CardMember = new CardMember();
        $CardGive = new CardGive();
        $card_id = $CardMember->where(['top_mid' => Session::get('login_top_mid')])->value('card_id');
        $map['card_id'] = $card_id;
        $putinfo = $CardGive->where($map)->find();
        if (request()->isAjax()) {
            $arr = request()->post();
            $data = $arr;
            $data['top_mid'] = Session::get('login_top_mid');
            $data['card_id'] = $card_id;
            $data['card_type'] = 'MEMBER_CARD';
            $data['is_put'] = 0;
            $data['give_type'] = 'fire_card';
            //END
            if ($arr['time_type'] == 'lasting' || $arr['time_type'] == ''){
                $data['begin_time'] = time();
                $data['end_time'] = strtotime("+10 year");
                $data['times'] =  $data['begin_time'] . " - ". $data['end_time'];
                $data['time_type'] = 'lasting';
            } else{
                $searchdate=explode(" - ", request()->param('give_date'));
                $data['begin_time'] = strtotime($searchdate[0]);
                $data['end_time'] = strtotime($searchdate[1]);
            }
            //END
            if (isset($arr['card_arr'])) {
                $card_arr = $this->card_zs_list($arr['card_arr']);
                $data['card_no'] = count($card_arr);
                $data['card_id_list'] = json_encode($card_arr, JSON_UNESCAPED_UNICODE);
            } else {
                $data['card_id_list'] = '';
                $data['card_no'] = 0;
            }
            if ($putinfo) {
                $data['update_time'] = time();
                $map['card_id'] = $card_id;
                $map['id'] = $putinfo['id'];
                $res = $CardGive->allowField(true)->save($data, $map);
            } else {
                $data['create_time'] = time();
                $res = $CardGive->allowField(true)->save($data);
            }
            if ($res){
                $resa = ['code'=>0,'message'=>'保存成功'];
            }else{
                $resa = ['code'=>9001,'message'=>'保存失败'];
            }
            return json($resa);
        } else {
            $list = $CardGive->where($map)->select();
            $this->assign('putinfo', $putinfo);
            $this->assign('card', $map);
            $this->assign('rutlist', $list);
            return $this->fetch();
        }
    }

    //激活送券微信
    public function firegives(Request $request)
    {
        if ($request->isAjax()){
            $param = $request->post();
            $CardGive = new CardGive();
            $map['top_mid'] = Session::get('login_top_mid');
            $map['id'] = $param['give_id'];
            $giveinfo = $CardGive->where($map)->field('card_id,top_mid,card_id_list,end_time')->find();
            //END
            $Platurl = new Platurl();
            $url['platurl'] = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
            //END
            $cardlist = json_decode($giveinfo['card_id_list'],true);
            $card = [];
            foreach ($cardlist as $k=>$v){
                if ($v['zs_no'] >$k && count($card)<5){
                    $card[] = $v['zs_card_id'];
                }
            }
            $cards = $card;
            $data['card_id'] = $giveinfo['card_id'];
            $data['member_card']['activate_msg_operation']['url_cell']['card_id_list'] = $cards;
            $data['member_card']['activate_msg_operation']['url_cell']['end_time'] = $giveinfo['end_time'];
            $data['member_card']['activate_msg_operation']['url_cell']['text'] = '赠送您优惠券，请注意查收';
            $data['member_card']['activate_msg_operation']['url_cell']['url'] = $url['platurl'].'/mobile.php?s=/cardget/getfirecard/momach_id/'.$giveinfo['top_mid'];
            $options = $this->options();
            $wxObj = new Wxobjopen($options);
            $res = $wxObj->updateUserCard($data);
            if ($res['errcode'] == 0){
                $datas['is_put'] = 1;
                $datas['member_card'] = json_encode($data,JSON_UNESCAPED_UNICODE);
                $datas['res_info'] = json_encode($res,JSON_UNESCAPED_UNICODE);
                $CardGive->allowField(true)->save($datas,$map);
                $rarr['code'] = 0;
                $rarr['message'] = '发布成功';
            }else{
                $rarr['code'] = 9001;
                $rarr['message'] = $res['errcode'].$res['errmsg'];
            }
            return json($rarr);
        }
    }

    //激活送券状态
    public function firegivesta()
    {
        $arr = request()->param();
        $data = $arr;
        $CardGive = new CardGive();
        $in = $CardGive->where(['id' => $arr['id'], 'card_id' => $arr['card_id']])->field('statu,is_put,end_time,top_mid,card_id_list')->find();
        //关闭
        if ($data['statu'] == 2){
            $today = strtotime(date("Y-m-d"),time());
            $datas['card_id'] = $arr['card_id'];
            $datas['member_card']['activate_msg_operation']['url_cell']['card_id_list'] = '';
            $datas['member_card']['activate_msg_operation']['url_cell']['end_time'] = $today;
            $datas['member_card']['activate_msg_operation']['url_cell']['text'] = '';
            $datas['member_card']['activate_msg_operation']['url_cell']['url'] = '';
        //开启
        }else{
            $Platurl = new Platurl();
            $url['platurl'] = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
            //END
            $cardlist = json_decode($in['card_id_list'],true);
            $card = [];
            foreach ($cardlist as $k=>$v){
                if ($v['zs_no'] >$k && count($card)<5){
                    $card[] = $v['zs_card_id'];
                }
            }
            $cards = $card;
            //END
            $datas['card_id'] = $arr['card_id'];
            $datas['member_card']['activate_msg_operation']['url_cell']['card_id_list'] = $cards;
            $datas['member_card']['activate_msg_operation']['url_cell']['end_time'] = $in['end_time'];
            $datas['member_card']['activate_msg_operation']['url_cell']['text'] = '赠送您优惠券，请注意查收';
            $datas['member_card']['activate_msg_operation']['url_cell']['url'] = $url['platurl'].'/mobile.php?s=/cardget/getfirecard/momach_id/'.$in['top_mid'];
        }
        $options = $this->options();
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->updateUserCard($datas);
        if ($res['errcode'] == 0) {
            $datasa['statu'] = $data['statu'] == 1 ? 2 : 1;
            $res = $CardGive->save($datasa, ['id' => $arr['id'], 'card_id' => $arr['card_id']]);
            if ($res) {
                $this->success('修改成功', url('marke/firegive'));
            } else {
                $this->error('修改失败', url('marke/firegive'));
            }
        }else{
            $this->error('修改失败', url('marke/firegive'));
        }
    }

    //激活送券删除
    public function firegivedel()
    {
        $arr = request()->param();
        $CardGive = new CardGive();
        $res = $CardGive->where(['id' => $arr['id'], 'card_id' => $arr['card_id']])->delete();
        if ($res) {
            $this->success('删除成功', url('marke/firegive'));
        } else {
            $this->error('删除失败', url('marke/firegive'));
        }
    }

    //冲送规则列表
    public function czgivelist($card_id)
    {
        $CardCzgive = new CardCzgive();
        $map['card_id'] = $card_id;
        $list = $CardCzgive->where($map)->select();
        $this->assign('list', $list);
        $this->assign('card', $map);
        return $this->fetch();
    }

    //冲送添加
    public function czgiveadd($card_id)
    {
        if (Request()->isPost()) {
            $arr = request()->post();
            $data['bonus'] = $arr['bonus'];
            $data['limit_sume'] = $arr['limit_sume'];
            $data['top_mid'] = Session::get('login_top_mid');
            $data['card_id'] = $card_id;
            $data['cz_money'] = $arr['cz_money'];
            $data['zs_money'] = $arr['zs_money'];
            if (isset($arr['zs_card_id'])) {
                $data['zs_card_id'] = implode(",", $arr['zs_card_id']);
                if (count($arr['zs_card_id']) > 1) {
                    $data['zs_card'] = 2;
                } else {
                    $data['zs_card'] = 1;
                }
            } else {
                $data['zs_card_id'] = '';
                $data['zs_card'] = 0;
            }
            $data['statu'] = $arr['statu'];
            $data['create_time'] = time();
            $CardCzgive = new CardCzgive();
            $res = $CardCzgive->save($data);
            if ($res == false) {
                $this->error('设置失败！', url('cardus/storagegl', ['card_id' => $card_id]));
            } else {
                $this->success('设置成功！', url('cardus/storagegl', ['card_id' => $card_id]));
            }
        } else {
            $CardGeneral = new CardGeneral();
            $mab['statu'] = 0;
            $mab['mid'] = ['in', $this->get_mer_mid()];
            $mab['end_timestamp'] = ['gt', time()];
            $card['card_id'] = $card_id;
            $cards = $CardGeneral->where($mab)->select();
            $this->assign('cards', $cards);
            return $this->fetch();
        }
    }

    //冲送添加
    public function czgiveadds($card_id)
    {
        if (Request()->isPost()) {
            $arr = request()->post();
            $arr['type'] = 1;
            $data['bonus'] = $arr['bonus'];
            $data['limit_sume'] = $arr['limit_sume'];
            $data['top_mid'] = Session::get('login_top_mid');
            $data['card_id'] = $card_id;
            $data['cz_money'] = $arr['cz_money'];
            $data['type'] = $arr['type'];
            $data['zs_money'] = $arr['zs_money'];
            $data['zs_show'] = $arr['zs_show'];
            if (isset($arr['card_arr'])) {
                $card_arr = $this->card_zs_list($arr['card_arr']);
//                $zs_card_id = array_filter($card_arr);
                $data['zs_card'] = count($card_arr);
                $data['zs_card_id_all'] = json_encode($card_arr, JSON_UNESCAPED_UNICODE);
            } else {
                $data['zs_card_id_all'] = '';
                $data['zs_card'] = 0;
            }
            $data['statu'] = $arr['statu'];
            $data['create_time'] = time();
//            return json($data);
            $CardCzgive = new CardCzgive();
            $res = $CardCzgive->allowField(true)->save($data);
            if ($res == false) {
                $this->error('设置失败！', url('cardus/storagegl', ['card_id' => $card_id]));
            } else {
                $this->success('设置成功！', url('cardus/storagegl', ['card_id' => $card_id]));
            }
        } else {
            $CardGeneral = new CardGeneral();
            $mab['statu'] = 0;
            $mab['mid'] = ['in', $this->get_mer_mid()];
            $mab['end_timestamp'] = ['gt', time()];
            $mab['is_cgive'] = 1;
            $mab['is_del'] = 1;
            $card['card_id'] = $card_id;
            $cards = $CardGeneral->where($mab)->select();
            $this->assign('cards', $cards);
            return $this->fetch();
        }
    }

    //卡券排列
    public function card_zs_list($data)
    {
//        $zs_card_id = $data['zs_card_id'];
        $arr = [];
        foreach ($data['zs_card_id'] as $k => $v) {
            $arr[] = [
                'zs_card_id' => $v,
                'zs_no' => $data['zs_no'][$k],
            ];
        }
//        $data['thumb'] = serialize($thumb);
//        $data['img'] = reset($image['img']);
        return $arr;
    }

    //冲送修改
    public function czgiveedit($id, $card_id)
    {
        if (Request()->isPost()) {
            $arr = request()->post();
            $data['bonus'] = $arr['bonus'];
            $data['bonus'] = $arr['bonus'];
            $data['limit_sume'] = $arr['limit_sume'];
            $data['cz_money'] = $arr['cz_money'];
            $data['zs_money'] = $arr['zs_money'];
            $data['statu'] = $arr['statu'];
            if (isset($arr['zs_card_id'])) {
                $data['zs_card_id'] = implode(",", $arr['zs_card_id']);
                if (count($arr['zs_card_id']) > 1) {
                    $data['zs_card'] = 2;
                } else {
                    $data['zs_card'] = 1;
                }
            } else {
                $data['zs_card_id'] = '';
                $data['zs_card'] = 0;
            }
            $data['update_time'] = time();
            $CardCzgive = new CardCzgive();
            $res = $CardCzgive->save($data, ['id' => $id]);
            if ($res == false) {
                $this->error('设置失败！', url('cardus/storagegl', ['card_id' => $card_id]));
            } else {
                $this->success('设置成功！', url('cardus/storagegl', ['card_id' => $card_id]));
            }
        } else {
            $CardCzgive = new CardCzgive();
            $info = $CardCzgive->where('id', $id)->find();
            $CardGeneral = new CardGeneral();
            $mab['statu'] = 0;
            $mab['mid'] = ['in', $this->get_mer_mid()];
            $mab['end_timestamp'] = ['gt', time()];
            $mab['is_del'] = 1;
            $cards = $CardGeneral->where($mab)->select();
            $this->assign('cards', $cards);
            $this->assign('info', $info);
            return $this->fetch();
        }
    }

    //冲送修改
    public function czgiveedits($id, $card_id)
    {
        if (Request()->isPost()) {
            $arr = request()->post();
            $data['bonus'] = $arr['bonus'];
            $data['limit_sume'] = $arr['limit_sume'];
            $data['top_mid'] = Session::get('login_top_mid');
            $data['cz_money'] = $arr['cz_money'];
            $data['zs_money'] = $arr['zs_money'];
            if (isset($arr['card_arr'])) {
                $card_arr = $this->card_zs_list($arr['card_arr']);
//                $zs_card_id = array_filter($card_arr);
                $data['zs_card'] = count($card_arr);
                $data['zs_card_id_all'] = json_encode($card_arr, JSON_UNESCAPED_UNICODE);
            } else {
                $data['zs_card_id_all'] = '';
                $data['zs_card'] = 0;
            }
            $data['zs_show'] = $arr['zs_show'];
            $data['statu'] = $arr['statu'];
            $data['update_time'] = time();
            $CardCzgive = new CardCzgive();
            $res = $CardCzgive->save($data, ['id' => $id]);
            if ($res == false) {
                $this->error('设置失败！', url('cardus/storagegl', ['card_id' => $card_id]));
            } else {
                $this->success('设置成功！', url('cardus/storagegl', ['card_id' => $card_id]));
            }
        } else {
            $CardCzgive = new CardCzgive();
            $info = $CardCzgive->where('id', $id)->find();
            $CardGeneral = new CardGeneral();
            $mab['statu'] = 0;
            $mab['mid'] = ['in', $this->get_mer_mid()];
            $mab['end_timestamp'] = ['gt', time()];
            $mab['is_cgive'] = 1;
            $mab['is_del'] = 1;
            $cards = $CardGeneral->where($mab)->select();
            foreach ($cards as $k => $v) {
                $cards[$k]['get_limit'] = getcardgetsume($v['card_id']);
            }
            $zs_card_id_all = json_decode($info['zs_card_id_all'], true);
            $this->assign('zs_card_id_all', $zs_card_id_all);
            $this->assign('cards', $cards);
            $this->assign('info', $info);
            return $this->fetch();
        }
    }

    //冲送设置
    public function czgivehigh($id, $card_id)
    {
        if (Request()->isPost()) {
            $arr = request()->post();
            $data = [
                'limit_sume' => $arr['limit_sume'],
                'bonus' => $arr['bonus'],
                'update_time' => time(),
            ];
            $CardCzgive = new CardCzgive();
            $res = $CardCzgive->save($data, ['id' => $id]);
            if ($res == false) {
                $this->error('设置失败！', url('cardus/storagegl', ['card_id' => $card_id]));
            } else {
                $this->success('设置成功！', url('cardus/storagegl', ['card_id' => $card_id]));
            }
        } else {
            $CardCzgive = new CardCzgive();
            $info = $CardCzgive->where('id', $id)->find();
            $this->assign('info', $info);
            return $this->fetch();
        }
    }

    //冲送状态
    public function czgivestatu()
    {
        if (Request()->isGet()) {
            $arr = request()->param();
            $CardCzgive = new CardCzgive();
            $data['statu'] = $CardCzgive->where('id', $arr['id'])->value('statu') == 1 ? 0 : 1;
            $res = $CardCzgive->save($data, ['id' => $arr['id']]);
            if ($res) {
                $this->success('修改成功！', url('cardus/storagegl', ['card_id' => $arr['card_id']]));
            } else {
                $this->error('修改失败！', url('cardus/storagegl', ['card_id' => $arr['card_id']]));
            }
        }
    }

    //冲送删除
    public function czgivedel($id, $card_id)
    {
        $CardCzgive = new CardCzgive();
        $res = $CardCzgive->where('id', $id)->delete();
        if ($res == false) {
            $this->error('删除失败！', url('cardus/storagegl', ['card_id' => $card_id]));
        } else {
            $this->success('删除成功！', url('cardus/storagegl', ['card_id' => $card_id]));
        }
    }

    //付费购券
    public function paypurcardslist()
    {
        $CardPaycard = new CardPaycard();
        $map['type'] = 2;
        $map['status'] = ['elt',2];
        $map['top_mid'] = Session::get('login_top_mid');
        $list = $CardPaycard->where($map)->order('status desc')->select();
        $Platurl = new Platurl();
        $notify_url = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
//        $notify_url = Config::get('sysconfig.notify_url');
        $mab2['type'] = 2;
        $mab2['top_mid'] = Session::get('login_top_mid');
        $card['mid'] = $CardPaycard->where($mab2)->value('mid');
        $card['url'] = $notify_url . '/mobile.php?s=/cardshop/paycardsinfo/';
        $card['shop_url'] = $notify_url . '/mobile.php?s=/cardshop/paycards/mid/' . $card['mid'];
        $this->assign('card', $card);
        $this->assign('list', $list);
        return $this->fetch();

    }

    public function paypurcardslog()
    {
        $CardPaycardlog = new CardPaycardlog();
        $map['fid'] = request()->param('fid');
        $map['paystatu'] = 1;
        $list = $CardPaycardlog->where($map)->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    //付费购券
    public function paypurcardsadd()
    {
        if (request()->isPost()) {
            $arr = request()->post();
            $data = $arr;
            $data['type'] = 2;
//            $data['mid'] = Session::get('login_mid');
//            $data['mid'] = $this->getmid($arr['cardlist']['zs_card_id'][0]);
            $data['top_mid'] = Session::get('login_top_mid');
            $times = explode(" - ", $arr['times']);
            $data['starttime'] = $times[0];
            $data['endtime'] = $times[1];
//            $cardlist = $this->card_zs_list($arr['cardlist']);
//            $data['cardlist'] = json_encode($cardlist,JSON_UNESCAPED_UNICODE);
//            $data['starttime'] = strtotime($data['starttime']);
//            $data['endtime'] = strtotime($data['endtime']);
            $CardPaycard = new CardPaycard();
            $res = $CardPaycard->allowField(true)->save($data);
            if ($res) {
                $this->success('添加成功！', url('marke/paypurcardslist'));
            } else {
                $this->error('添加失败！', url('marke/paypurcardslist'));
            }
        } else {
            $map['id'] = ['in', $this->get_mer_mid()];
            $map['wx_open_id'] = ['neq', ''];
            $Merchant = new Merchant();
            $mach = $Merchant->where($map)->select();
//            $this->assign('moinfo',$moinfo);
            $this->assign('mach', $mach);
            return $this->fetch();
        }
    }

    //高级设置
    public function wxputsetup(){

        $WxOpen = new WxOpen();
        $CardFansNotice = new CardFansNotice();
        $Momerchant = new Momerchant();
        $wx_open_id = $Momerchant->where(['id'=>Session::get('login_top_mid')])->value('wx_open_id');
        $wxopeninfo = $WxOpen->where(['id'=>$wx_open_id])->field('id,fans_notice_cards_list,gh_id')->find();
        $info = $CardFansNotice->where(['top_mid'=>Session::get('login_top_mid')])->find();
        if ($wxopeninfo){
            if (Request()->isAjax()){
                $arr = request()->post();
//                return json($arr);
                $data['top_mid'] = Session::get('login_top_mid');
                $data['gh_id'] = $wxopeninfo['gh_id'];
                $data['wx_open_id'] = $wx_open_id;
                $data['img_url'] = $arr['img_url'];
                $data['status'] = $arr['status'];
                $data['addtime'] = time();
//                return json($data);
                if ($info){
                    $res = $CardFansNotice->allowField(true)->save($data,['top_mid'=>Session::get('login_top_mid')]);
                }else{
                    $res = $CardFansNotice->allowField(true)->save($data);
                }
                if ($res){
                    $resa = ['code'=>0,'message'=>'success'];
                }else{
                    $resa = ['code'=>9001,'message'=>'error'];
                }
                return json($resa);
            }else{
                if (!$info){
                    $info['status'] = 0;
                    $info['img_url'] = '';
                }
//                var_dump($info);
                $this->assign('info', $info);
                return $this->fetch();
            }
        }else{
            $this->error('请授权公众号之后再来设置');
        }

    }

    //付费购券
    public function paypurcardsedit(Request $request)
    {
        if (request()->isPost()) {
            $data = request()->post();
//            return json($data);
            $times = explode(" - ", $data['times']);
            $data['starttime'] = $times[0];
            $data['endtime'] = $times[1];

            $CardPaycard = new CardPaycard();
            $res = $CardPaycard->allowField(true)->save($data, array('id' => $data['id']));
            if ($res) {
                $this->success('修改成功！', url('marke/paypurcardslist'));
            } else {
                $this->error('修改失败！', url('marke/paypurcardslist'));
            }
        } else {
            $param = $request->param();
            $CardPaycard = new CardPaycard();
            $info = $CardPaycard->where(array('id' => $param['id']))->find();
            $this->assign('info', $info);
            //END
            $map['id'] = ['in', $this->get_mer_mid()];
            $map['wx_open_id'] = ['neq', ''];
            $Merchant = new Merchant();
            $mach = $Merchant->where($map)->select();
            $this->assign('mach', $mach);
            //END
            return $this->fetch();
        }
    }

    public function paypurcardsinfo()
    {
        $CardPaycard = new CardPaycard();
        $id = request()->param('id');

        $info = $CardPaycard->where(array('id' => $id))->find();
        $this->assign('info', $info);
        return $this->fetch();

    }

    //付费购券
    public function paypurcardsdel()
    {
        $id = request()->param('id');
        $CardPaycard = new CardPaycard();
        $res = $CardPaycard->where(['id' => $id])->delete();
        if ($res) {
            $this->success('删除成功！', url('marke/paypurcardslist'));
        } else {
            $this->error('删除失败！', url('marke/paypurcardslist'));
        }
    }

    //付费购券
    public function paypurcardsstatu()
    {
        $id = request()->post('id');

        $CardPaycard = new CardPaycard();
        $payinfo = $CardPaycard->where(['id' => $id])->field('status')->find();
        $data['status'] = $payinfo['status'] == 1 ? 0 : 1;


        $res = $CardPaycard->where(['id' => $id])->update($data);
        if ($res) {
            $rarr['code'] = 0;
            $rarr['msg'] = '成功';
        } else {
            $rarr['code'] = 9001;
            $rarr['msg'] = '失败';
        }
        return json($rarr);
    }

    /*
     * 支付宝
     *
     * */
    //冲送修改
    public function czgiveeditali($id, $template_id)
    {
        if (Request()->isPost()) {
            $arr = request()->post();
            $data['bonus'] = $arr['bonus'];
            $data['bonus'] = $arr['bonus'];
            $data['limit_sume'] = $arr['limit_sume'];
            $data['cz_money'] = $arr['cz_money'];
            $data['zs_money'] = $arr['zs_money'];
            $data['statu'] = $arr['statu'];
            if (isset($arr['zs_template_id'])) {
                $data['zs_template_id'] = implode(",", $arr['zs_card_id']);
                if (count($arr['zs_template_id']) > 1) {
                    $data['zs_card'] = 2;
                } else {
                    $data['zs_card'] = 1;
                }
            } else {
                $data['zs_template_id'] = '';
                $data['zs_card'] = 0;
            }
            $data['update_time'] = time();
            $CardCzgive = new CardCzgive();
            $res = $CardCzgive->save($data, ['id' => $id]);
            if ($res == false) {
                $this->error('设置失败！', url('alicards/storageglali', ['template_id' => $template_id]));
            } else {
                $this->success('设置成功！', url('alicards/storageglali', ['template_id' => $template_id]));
            }
        } else {
            $CardCzgive = new CardCzgive();
            $info = $CardCzgive->where('id', $id)->find();
            $CardGeneral = new CardGeneral();
            $mab['statu'] = 0;
            $mab['mid'] = ['in', $this->get_mer_mid()];
            $mab['end_timestamp'] = ['gt', time()];
            $cards = $CardGeneral->where($mab)->select();
            $this->assign('cards', $cards);
            $this->assign('info', $info);
            return $this->fetch();
        }
    }

    //冲送设置
    public function czgivehighali($id, $template_id)
    {
        if (Request()->isPost()) {
            $arr = request()->post();
            $data = [
                'limit_sume' => $arr['limit_sume'],
                'bonus' => $arr['bonus'],
                'update_time' => time(),
            ];
            $CardCzgive = new CardCzgive();
            $res = $CardCzgive->save($data, ['id' => $id]);
            if ($res == false) {
                $this->error('设置失败！', url('alicards/storageglali', ['template_id' => $template_id]));
            } else {
                $this->success('设置成功！', url('alicards/storageglali', ['template_id' => $template_id]));
            }
        } else {
            $CardCzgive = new CardCzgive();
            $info = $CardCzgive->where('id', $id)->find();
            $this->assign('info', $info);
            return $this->fetch();
        }
    }

    //冲送状态
    public function czgivestatuali()
    {
        if (Request()->isGet()) {
            $arr = request()->param();
            $CardCzgive = new CardCzgive();
            $data['statu'] = $CardCzgive->where('id', $arr['id'])->value('statu') == 1 ? 0 : 1;
            $res = $CardCzgive->save($data, ['id' => $arr['id']]);
            if ($res) {
                $this->error('修改成功！', url('alicards/storageglali', ['template_id' => $arr['template_id']]));
            } else {
                $this->success('修改失败！', url('alicards/storageglali', ['template_id' => $arr['template_id']]));
            }
        }
    }

    //冲送删除
    public function czgivedelali($id, $template_id)
    {
        $CardCzgive = new CardCzgive();
        $res = $CardCzgive->where('id', $id)->delete();
        if ($res == false) {
            $this->error('删除失败！', url('alicards/storageglali', ['template_id' => $template_id]));
        } else {
            $this->success('删除成功！', url('alicards/storageglali', ['template_id' => $template_id]));
        }
    }

    //关注送券
    public function followputcards()
    {
        $CardFollowcard = new CardFollowcard();
        $CardFreecard = new CardFreecard();
        if (Request()->isAjax()) {
            $arr = request()->post();

            $data = [];
            $data = $arr;

            if ($arr['time_type'] == 'lasting' || $arr['time_type'] == ''){
                $data['starttime'] = date('Y-m-d h:i:s',time());
                $data['endtime'] = date('Y-m-d h:i:s',strtotime("+10 year"));
                $data['times'] =  $data['starttime'] . " - ". $data['endtime'];
                $data['time_type'] = 'lasting';
            }else{
                $times = explode(" - ", $arr['times']);
                $data['starttime'] = $times[0];
                $data['endtime'] = $times[1];
            }
            $data['top_mid'] = Session::get('login_top_mid');
            $data['cardlist'] = $CardFreecard->where(['id' => $arr['free_id']])->value('cardlist');
            $cardlist = $CardFollowcard->where(['top_mid' => Session::get('login_top_mid')])->value('id');

            if ($cardlist) {
                $res = $CardFollowcard->allowField(true)->save($data, ['id' => $arr['id']]);
            } else {
                $res = $CardFollowcard->allowField(true)->save($data);
            }
            if ($res){
                $resa = ['code'=>0,'message'=>'保存成功'];
            }else{
                $resa = ['code'=>9001,'message'=>'保存失败'];
            }
            return json($resa);
        } else {
            $map['top_mid'] = Session::get('login_top_mid');
            $CardFreecard = new CardFreecard();
            $mab['type'] = 1;
            $mab['top_mid'] = Session::get('login_top_mid');
            $mab['is_follow'] = 1;
            $freecard = $CardFreecard->where($mab)->select();

            $list = $CardFollowcard->where($map)->select();
            $info = $CardFollowcard->where($map)->find();
            $this->assign('freecard', $freecard);
            $this->assign('info', $info);
            $this->assign('list', $list);
            return $this->fetch();
        }
    }

    //关注送券开关
    public function followputstatu()
    {
        $id = request()->param('id');
        if ($id) {
            $CardFollowcard = new CardFollowcard();
            $payinfo = $CardFollowcard->where(['id' => $id])->field('status')->find();
            $data['status'] = $payinfo['status'] == 1 ? 0 : 1;
            $res = $CardFollowcard->where(['id' => $id])->update($data);
            if ($res) {
                $this->success('修改成功！', url('marke/followputcards'));
            } else {
                $this->error('修改失败！', url('marke/followputcards'));
            }
        }
    }

    //关注送券记录
    public function followputlog()
    {
        $CardFollowcardlog = new CardFollowcardlog();
        $map['fid'] = request()->param('fid');

        $map['top_mid'] = Session::get('login_top_mid');
        $list = $CardFollowcardlog->where($map)->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    //免费券列表

    //免费券
    public function freecardslist()
    {
        $CardFreecard = new CardFreecard();
        $map['type'] = 1;
        $map['top_mid'] = Session::get('login_top_mid');
        $list = $CardFreecard->where($map)->order('status desc')->select();
        $Platurl = new Platurl();
        $notify_url = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
        $mab2['type'] = 1;
        $mab2['top_mid'] = Session::get('login_top_mid');
        $card['mid'] = $CardFreecard->where($mab2)->value('mid');
        $card['url'] = $notify_url . '/mobile.php?s=/cardshopnu/freecardsinfo/';
        $card['shop_url'] = $notify_url . '/mobile.php?s=/cardshopnu/freecards/mid/' . $card['mid'];
        $this->assign('card', $card);
        $this->assign('list', $list);
        return $this->fetch();

    }

    //免费券
    public function freecardslog()
    {
        $CardFreecardlog = new CardFreecardlog();
        $map['fid'] = request()->param('fid');
        $map['paystatu'] = 1;
        $list = $CardFreecardlog->where($map)->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    //免费券
    public function freecardsadd()
    {
        if (request()->isPost()) {
            $arr = request()->post();
            $data = $arr;
            $data['type'] = 1;
            $times = explode(" - ", $arr['times']);
            $data['starttime'] = $times[0];
            $data['endtime'] = $times[1];
            $data['top_mid'] = Session::get('login_top_mid');
//            $data['starttime'] = strtotime($arr['starttime']);
//            $data['endtime'] = strtotime($arr['endtime'])+86399;
//            var_dump(json_encode($data,JSON_UNESCAPED_UNICODE));
//            exit();
            $CardFreecard = new CardFreecard();
            $res = $CardFreecard->allowField(true)->save($data);
            if ($res) {
                $this->success('添加成功！', url('marke/freecardslist'));
            } else {
                $this->error('添加失败！', url('marke/freecardslist'));
            }
        } else {
            $map['id'] = ['in', $this->get_mer_mid()];
            $map['wx_open_id'] = ['neq', ''];
            $Merchant = new Merchant();
            $mach = $Merchant->where($map)->select();
//            $this->assign('moinfo',$moinfo);
            $this->assign('mach', $mach);
            return $this->fetch();
        }
    }

    //免费券
    public function freecardsedit(Request $request)
    {
        if (request()->isPost()) {
            $data = request()->post();

            $times = explode(" - ", $data['times']);
            $data['starttime'] = $times[0];
            $data['endtime'] = $times[1];
            $data['top_mid'] = Session::get('login_top_mid');
            $CardFreecard = new CardFreecard();
            $res = $CardFreecard->allowField(true)->save($data, array('id' => $data['id']));
            if ($res) {
                $this->success('修改成功！', url('marke/freecardslist'));
            } else {
                $this->error('修改失败！', url('marke/freecardslist'));
            }
        } else {
            $param = $request->param();
            $CardFreecard = new CardFreecard();
            $info = $CardFreecard->where(array('id' => $param['id']))->find();
            $this->assign('info', $info);
            $map['id'] = ['in', $this->get_mer_mid()];
            $map['wx_open_id'] = ['neq', ''];
            $Merchant = new Merchant();
            $mach = $Merchant->where($map)->select();
            $this->assign('mach', $mach);
            return $this->fetch();
        }
    }

    //免费券
    public function freecardsinfo()
    {
        $CardFreecard = new CardFreecard();
        $id = request()->param('id');

        $info = $CardFreecard->where(array('id' => $id))->find();
        $this->assign('info', $info);
        return $this->fetch();

    }

    //免费券
    public function freecardsdel()
    {
        $id = request()->param('id');
        $CardFreecard = new CardFreecard();
        $res = $CardFreecard->where(['id' => $id])->delete();
        if ($res) {
            $this->success('删除成功！', url('marke/freecardslist'));
        } else {
            $this->error('删除失败！', url('marke/freecardslist'));
        }
    }

    //免费券
    public function freecardsstatu()
    {
        $id = request()->post('id');

        $CardFreecard = new CardFreecard();
        $payinfo = $CardFreecard->where(['id' => $id])->field('status')->find();
        $data['status'] = $payinfo['status'] == 1 ? 0 : 1;


        $res = $CardFreecard->where(['id' => $id])->update($data);
        if ($res) {
            $rarr['code'] = 0;
            $rarr['msg'] = '成功';
        } else {
            $rarr['code'] = 9001;
            $rarr['msg'] = '失败';
        }
        return json($rarr);
    }

    public function getfreecardslist(Request $request){
        if ($request->isAjax()) {
            $param = $request->post();
//            return json($param);
            $CardGen = new CardGeneral();
            $CardFreecard = new CardFreecard();
            $info = $CardFreecard->where(array('id' => $param['id']))->find();
            $zs_card_id_all = json_decode($info['cardlist'], true);
            $cardlist = [];
            foreach ($zs_card_id_all as $k=>$v){
                $cardinfo = $CardGen->where('card_id',$v['zs_card_id'])->field('get_limit,title')->find();
                $cardlist[$k]['title'] = $cardinfo['title'];
                $cardlist[$k]['card_id'] = $v['zs_card_id'];
                $cardlist[$k]['get_limit'] = $cardinfo['get_limit'];
                $cardlist[$k]['zs_no'] = $v['zs_no'];
            }
            return json($cardlist);
        }
    }

    /*
     *
     * 点击自定义菜单送券
     *
     *
     * */

    //点击自定义菜单送券
    public function clickputcards()
    {
        $CardClickput = new CardClickReplyPut();
        $map['top_mid'] = Session::get('login_top_mid');

        $list = $CardClickput->where($map)->select();

        $this->assign('list', $list);
        return $this->fetch();

    }

    //点击自定义菜单送券
    public function clickputcardsadd()
    {
        $CardClickput = new CardClickReplyPut();
        $CardFreecard = new CardFreecard();
        $CardPaycard = new CardPaycard();
        if (Request()->isAjax()) {
            $arr = request()->post();
            $data = [];
            $data = $arr;
            if ($data['time_type'] == 'lasting' || $data['time_type'] == ''){
                $data['starttime'] = date('Y-m-d h:i:s',time());
                $data['endtime'] = date('Y-m-d h:i:s',strtotime("+10 year"));
                $data['times'] =  $data['starttime'] . " - ". $data['endtime'];
                $data['time_type'] = 'lasting';
            }else{
                $times = explode(" - ", $data['times']);
                $data['starttime'] = $times[0];
                $data['endtime'] = $times[1];
            }
            $data['top_mid'] = Session::get('login_top_mid');
            if ($arr['give_type'] == 1) {
                $data['cardlist'] = $CardFreecard->where(['id' => $arr['free_id']])->value('cardlist');
                $matter_type = 'free_';
            } else {
                $data['cardlist'] = $CardPaycard->where(['id' => $arr['paycard_id']])->value('cardlist');
                $matter_type = 'paycard_';
            }

            $res = $CardClickput->allowField(true)->save($data);

            if ($res) {
                $id = $CardClickput->id;
                $datas['click_key'] = 'matter_' . $matter_type . $id;
                $CardClickput->allowField(true)->save($datas, ['id' => $id]);
                $resa = ['code'=>0,'message'=>'保存成功'];
            } else {
                $resa = ['code'=>9001,'message'=>'保存失败'];
            }
            return json($resa);
        } else {
            $map['top_mid'] = Session::get('login_top_mid');
            $CardFreecard = new CardFreecard();
            $mab['type'] = 1;
            $mab['top_mid'] = Session::get('login_top_mid');
            $mab['is_follow'] = 0;
            $mab['status'] = 1;
            $mab['endtime'] = ['gt',time()];
            $freecard = $CardFreecard->where($mab)->select();
            $mac['type'] = 2;
            $mac['status'] = 1;
            $mac['top_mid'] = Session::get('login_top_mid');
            $mac['endtime'] = ['gt',time()];
            $paycard = $CardPaycard->where($mac)->select();
            $this->assign('paycard', $paycard);
            $this->assign('freecard', $freecard);
            return $this->fetch();
        }
    }

    //点击自定义菜单送券详情
    public function clickputcardsinfo()
    {
        $CardClickput = new CardClickReplyPut();
        $map['id'] = request()->param('id');

        $info = $CardClickput->where($map)->find();

        $this->assign('info', $info);
        return $this->fetch();

    }

    //点击自定义菜单送券开关
    public function clickputstatu()
    {
        $id = request()->param('id');
        if ($id) {
            $CardClickput = new CardClickReplyPut();
            $payinfo = $CardClickput->where(['id' => $id])->field('status')->find();
            $data['status'] = $payinfo['status'] == 1 ? 0 : 1;
            $res = $CardClickput->where(['id' => $id])->update($data);
            if ($res) {
                $this->success('修改成功！', url('marke/clickputcards'));
            } else {
                $this->error('修改失败！', url('marke/clickputcards'));
            }
        }
    }

    //点击自定义菜单送券记录
    public function clickputlog()
    {
        $CardClickputlog = new CardClickReplyPutlog();
        $map['click_id'] = request()->param('id');
        $map['top_mid'] = Session::get('login_top_mid');
        $list = $CardClickputlog->where($map)->select();
        $this->assign('list', $list);
        return $this->fetch();
    }


    //新人有礼
    public function newcourtesy()
    {
        return $this->fetch();
    }

    //群发卡券  原生
    public function masscard()
    {
        if (Request()->isPost()) {
            $arr = request()->post();
//            return json($arr);
//            exit();
            $options = $this->options();
            $weObj = new Wxobjopen($options);
            //粉丝群发
            $data = $this->getsendall($arr);
            $res = $weObj->mesgSendAll($data);
            if ($res['errcode'] == 0) {
                $sdata['top_mid'] = Session::get('login_top_mid');
                $sdata['card_id'] = $arr['card_id'];
                $adata['rule_name'] = $arr['rulename'];
                $sdata['MEMBER_CARD'] = getcardtype($arr['card_id']);
                $sdata['put_info'] = json_encode($data, JSON_UNESCAPED_UNICODE);
                $sdata['res_info'] = json_encode($res, JSON_UNESCAPED_UNICODE);
                $sdata['creattime'] = time();
                $CardPutRule = new CardPutRule();
                $res = $CardPutRule->allowField(true)->save($sdata);
                if ($res == false) {
                    echo "存入失败";
                } else {
                    echo "投放成功";
                }
            } else {
                echo "创建失败";
            }
        } else {
            $mid = $this->get_mer_mid();
            $map['statu'] = 0;
            $map['mid'] = ['in', $mid];
            $mab['statu'] = 0;
            $top_mid = Session::get('login_top_mid');
            $mab['top_mid'] = ['in', $top_mid];
            $mab['end_timestamp'] = ['gt', time()];
            $CardPutRule = new CardPutRule();
            $CardGeneral = new CardGeneral();
            $CardMember = new CardMember();
            $mab['is_put'] = 1;

            $cards = $CardGeneral->where($mab)->select();
            $cardus = $CardMember->where($map)->select();

            $cardu = $CardPutRule->where($map)->select();


            $this->assign('cardus', $cardus);
            $this->assign('cardu', $cardu);
            $this->assign('cards', $cards);

            return $this->fetch();
        }
    }

    //群发卡券
    public function getSendall($arr)
    {
        $data['filter']['is_to_all'] = true;
        $data['msgtype'] = 'wxcard';
        $data['wxcard'] = ['card_id' => $arr['card_id']];
        return $data;
    }

    //分组发送
    public function masstpl()
    {
        if (Request()->isPost()) {
            $arr = request()->post();
            $CardPutRuleMass = new CardPutRuleMass();
            $CardGeneral = new CardGeneral();
            $data = $arr;
            $data['remark'] = $arr['remark'];
            $data['first'] = $arr['first'];
            $data['card_id'] = $arr['card_id'];
            $data['card_title'] = $CardGeneral->where('card_id', $arr['card_id'])->value('title');
            $data['card_type'] = $CardGeneral->where('card_id', $arr['card_id'])->value('card_type');
            $data['creattime'] = time();
            $data['rule_name'] = $arr['rule_name'];
            $data['top_mid'] = Session::get('login_top_mid');
            $res = $CardPutRuleMass->allowField(true)->save($data);
            if ($res) {
                $this->success('规则设置成功', 'marke/masstpl');
            } else {
                $this->error('规则设置失败', 'marke/masstpl');
            }
        } else {
            $top_mid = Session::get('login_top_mid');
            $map['top_mid'] = $top_mid;
            $mab['statu'] = 0;
            $mab['top_mid'] = $top_mid;
            $mab['end_timestamp'] = ['gt', time()];
            $Momerchant = new Momerchant();
            $wx_open_id = $Momerchant->where('id', $mab['top_mid'])->value('wx_open_id');
            $CardPutRuleMass = new CardPutRuleMass();
            $CardGeneral = new CardGeneral();
            $CardFansGroupDict = new CardFansGroupDict();
            $mab['is_put'] = 1;
            $cards = $CardGeneral->where($mab)->select();
            $rule = $CardPutRuleMass->where($map)->select();
            $grouplist = $CardFansGroupDict->where(['wx_open_id' => $wx_open_id])->select();
            $this->assign('rulelist', $rule);
            $this->assign('cards', $cards);
            $this->assign('grouplist', $grouplist);
            return $this->fetch();
        }
    }

    //分组发送执行
    public function zx_massput()
    {
        $arr = request()->param();
        $CardPutRuleMass = new CardPutRuleMass();
        $CardFans = new CardFans();
        $CardGeneral = new CardGeneral();
        $Momerchant = new Momerchant();
        $top_mid = Session::get('login_top_mid');
        $mab['top_mid'] = $top_mid;
        $wx_open_id = $Momerchant->where('id', $mab['top_mid'])->value('wx_open_id');
        $rule = $CardPutRuleMass->where('id', $arr['id'])->find();
        $groupid = $rule['groupid'];
        $card_id = $rule['card_id'];
        $card = $CardGeneral->where('card_id', $card_id)->find();
        $userlist = $CardFans->where(['wx_open_id' => $wx_open_id, 'group' => $groupid])->field('nickname,openid')->select();
        if ($userlist) {
            foreach ($userlist as $k => $v) {
                $user['top_mid'] = $top_mid;
                $user['first'] = $rule['first'];
                $user['remark'] = $rule['remark'];
                $user['title'] = $card['title'];
                $user['card_id'] = $card['card_id'];
                $user['openid'] = $v['openid'];
                $user['nickname'] = $v['nickname'];
                $res[] = action('merchant/jobmach/mass_tpl_card', array($user));
            }
        } else {
            $res = [];
        }
        $is_statu = $rule['statu'];
        if ($is_statu == 0) {
            $datass['statu'] = 1;
            $CardPutRuleMass->save($datass, ['id' => $arr['id']]);
        }
        $this->success('已执行任务，请等待，在此期间可以进行其他操作。');
    }

    //指定会员单独发送  模板消息
    public function putCard()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardMember = new CardMember();
            $CardGeneral = new CardGeneral();
            $card_type = $this->gettype($arr['card_id']);
            if ($card_type == 'MEMBER_CARD') {
                $data = $CardMember->where('card_id', $arr['card_id'])->find();
            } else {
                $data = $CardGeneral->where('card_id', $arr['card_id'])->find();
            }
            $arrs['openid'] = $arr['openid'];
            $arrs['name'] = $arr['nickname'];
            $arrs['title'] = $data['title'];
            $arrs['card_id'] = $arr['card_id'];
            $res = action('Wxtemlpmesg/putCard', [$arrs]);
            if ($res['errcode'] == 0) {
                $arrss['code'] = '0';
                $arrss['message'] = '发送成功！';
            } else {
                $arrss['code'] = $res['errcode'];
                $arrss['message'] = '发送失败！'.$res['errmsg'];
            }
            return json($arrss);
        }
    }


    //导入excel
    public function importuser()
    {
        $CardLeaduser = new CardLeaduser();
        //搜索
        $p_data = request()->get();
        unset($p_data['page']);
        if ($p_data) {
            if ($p_data['name'] !== '') {
                $map['name'] = array('like', '%' . trim($p_data['nickname']) . '%');
            }
            if ($p_data['old_code'] !== '') {
                $map['old_code'] = $p_data['old_code'];
            }
            if ($p_data['statu'] !== '') {
                $map['statu'] = $p_data['statu'];
            }
        } else {
            $p_data['name'] = '';
            $p_data['old_code'] = '';
            $p_data['statu'] = '';
        }
        $mapuser['mid'] = ['in', $this->get_mer_mid()];
        $user['count'] = $CardLeaduser->where($mapuser)->count('id');
        $mapuser['statu'] = 1;
        $user['syn'] = $CardLeaduser->where($mapuser)->count('id');
        $mapuser['statu'] = 0;
        $user['notsyn'] = $CardLeaduser->where($mapuser)->count('id');

        $map['mid'] = ['in', $this->get_mer_mid()];
        $list = $CardLeaduser->where($map)->paginate(20);
        $Merchant = new Merchant();
        $mab['id'] = ['in', $this->get_mer_mid()];
        $mach = $Merchant->where($mab)->paginate(20);
        $this->assign('user', $user);
        $this->assign('mach', $mach);
        $this->assign('list', $list);// 赋值数据集
        return $this->fetch();
    }

    //删除导入会员
    public function deluser()
    {
        if (Request()->isGet()) {
            $arr = request()->param();
            $CardLeaduser = new CardLeaduser();
            $map['id'] = $arr['id'];
            $res = $CardLeaduser->where($map)->delete();
            if ($res) {
                $this->success('删除成功', 'marke/importuser');
            } else {
                $this->error('删除成功', 'marke/importuser');
            }
        }
    }

    //会员同步设置
    public function synsetup()
    {
        $CardMember = new CardMember();
        if (Request()->isPost()) {
            $arr = request()->param();
            $data['syn_is_exist'] = $arr['syn_is_exist'];
            $map['card_id'] = $arr['card_id'];
            $res = $CardMember->save($data, $map);
            if ($res) {
                $this->success('设置成功', 'marke/synsetup');
            } else {
                $this->error('设置失败', 'marke/synsetup');
            }
        } else {
            $mid = $this->get_mer_mid();
            if ($mid !== '') {
                $map['mid'] = ['in', $mid];
            } else {
                $map['top_mid'] = Session::get('login_top_mid');
            }
            $card = $CardMember->where($map)->find();
            $this->assign('card', $card);
            return $this->fetch();
        }
    }

    //类别
    public function gettype($card_id)
    {
        $map['card_id'] = $card_id;
        $CardMember = new CardMember();
        $type = $CardMember->where($map)->value('card_type');
        if (empty($type)) {
            $CardGeneral = new CardGeneral();
            $type = $CardGeneral->where($map)->value('card_type');
            return $type;
        } else {
            return $type;
        }
    }

    //微信API参数 根据mid获取
    public function option($mid)
    {
        Session::set('openid', null);
        $System = new System();
        $WxOpen = new WxOpen();
        $Merchant = new Merchant();
        $Agent = new Agent();
        $merchantinfo = $Merchant->where('id', $mid)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    public function options()
    {
        Session::set('openid', null);
        $top_mid = Session::get('login_top_mid');
        $Momerchant = new Momerchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $momerchantinfo = $Momerchant->where('id', $top_mid)->field('wx_open_id,agent')->find();
        $wx_open_id = $momerchantinfo['wx_open_id'];
//        $config = $System->where(['id' => 1])->find();
        $config = $Agent->where(['id' => $momerchantinfo['agent']])->find();
        $users = $WxOpen->where(['id' => $wx_open_id])->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //商户ID
    public function getmid($card_id)
    {
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id' => $card_id])->value('mid');
        if (empty($top_mid)) {
            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
            return $top_mid;
        } else {
            return $top_mid;
        }
    }

    //商户ID
    public function gettopmid($card_id)
    {
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id' => $card_id])->value('top_mid');
        if (empty($top_mid)) {
            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('top_mid');
            return $top_mid;
        } else {
            return $top_mid;
        }
    }

    public function gamcash()
    {
        $CardGamcash = new CardGamcash();
        if(request()->isPost()){
            $sarr=request()->post();
            $times=explode(" - ",$sarr['times']);
            $basic_info['activity_bg_color']=$sarr['color'];
            $basic_info['activity_tinyappid']=$sarr['activity_tinyappid'];
            $basic_info['begin_time']=strtotime($times[0]);
            $basic_info['end_time']=strtotime($times[1]);
            $basic_info['gift_num']=$sarr['gift_num'];
            $basic_info['max_partic_times_act']=$sarr['max_partic_times_act'];
            $basic_info['max_partic_times_one_day']=$sarr['max_partic_times_one_day'];
            $basic_info['mch_code']=$sarr['mch_code'];
            $card_info_list['card_id']=$sarr['card_id'];
            $card_info_list['min_amt']=$sarr['min_amt'] * 100;
            $card_info_list['total_user']=true;
            $info=array('info'=>array('basic_info'=>$basic_info,'card_info_list'=>array($card_info_list)));

            if ($basic_info['begin_time']+7200 < time()){
                $this->error('设置失败，参数错误:开始时间需大于当前时间两小时','','',30);
            }

            $options = $this->options();
            $weObj = new Wxobjopen($options);
            $sinfo=$weObj->activemkt($info);
            if($sinfo){
                if($sinfo['errcode']==0){
                    $data['mid'] = $sarr['mid'];        //mid
                    $data['top_mid'] = Session::get('login_top_mid');       //top_mid
                    $data['card_id'] = $sarr['card_id'];        //card_id
                    $data['mch_code'] = $sarr['mch_code'];        //商户号
                    $data['title'] = $sarr['title'];        //卡券
                    $data['activity_tinyappid'] = $sarr['activity_tinyappid'];        //小程序APPID
                    $data['min_amt'] = $sarr['min_amt'];            //门槛
                    $data['gift_num'] = $sarr['gift_num'];          //裂变数量
                    $data['color'] = $sarr['color'];                //颜色
                    $data['activity_info'] = json_encode($info,JSON_UNESCAPED_UNICODE);     //全部数据
                    $data['activity_id'] = $sinfo['activity_id'];           //活动ID
                    $data['activity_time'] = time();                        //时间

                    $data['begin_timestamp'] = $basic_info['begin_time'];          //开始时间
                    $data['end_timestamp'] = $basic_info['end_time'];                //结束时间
                    $CardGamcash->allowField(true)->save($data);
                    $this->success("设置成功，活动id:".$sinfo['activity_id']."请到微信商户平台激活活动");
                }else{
                    $this->error('设置失败，参数错误'.json_encode($sinfo,JSON_UNESCAPED_UNICODE),'','',30);
                }
            }
        }else{
            $CardGeneral = new CardGeneral();
            $mab['statu'] = 0;
            $mab['is_minus'] = 1;
            $mab['mid'] = ['in', $this->get_mer_mid()];
            $mab['end_timestamp'] = ['gt', time()];
            $cardlist=array();
            $cards = $CardGeneral->where($mab)->field('card_id,title')->select();
            foreach ($cards as $k=>$v){
                $cardlist[$k]['title'] = $v['title'];
                $cardlist[$k]['card_id'] = $v['card_id'];
                $cardlist[$k]['get_limit'] = getcardgetsume($v['card_id']);
            }
            $this->assign('cardlist',$cardlist);
            //列表
//            $map['statu'] = 0;
//            $map['is_minus'] = 1;
            $map['mid'] = ['in', $this->get_mer_mid()];
            $map['activity_id'] = ['neq', ''];
            $cardslist = $CardGamcash->where($map)->paginate('20');
//            var_dump($CardGamcash->getLastSql());
            $this->assign('list',$cardslist);
            return $this->fetch();
        }
    }

    public function gamcashlist()
    {
        $CardGeneral = new CardGeneral();
        $mab['statu'] = 0;
        $mab['is_minus'] = 1;
        $mab['mid'] = ['in', $this->get_mer_mid()];
        $mab['activity_id'] = ['neq', ''];
        $cards = $CardGeneral->where($mab)->select();
        $this->assign('list',$cards);
        return $this->fetch();
    }



    //获取卡券信息
    public function getcardsinfo(){
        if (Request()->isAjax()){
            $arr = request()->post();
//            return json($arr);
            $CardGeneral = new CardGeneral();
            $Merchant = new Merchant();
            $cardinfo = $CardGeneral->where(['card_id'=>$arr['card_id']])->field('title,mid,begin_timestamp,end_timestamp')->find();
            $mch_id = $Merchant->where(['id'=>$cardinfo['mid']])->value('sub_mch_id');
            if ($mch_id){
                $data['code'] = 0;
                $data['msg'] = 'success';
                $data['mid'] = $cardinfo['mid'];
                $data['title'] = $cardinfo['title'];
                $data['mch_id'] = $mch_id;
                if ($cardinfo['begin_timestamp'] - 1800 < time()){
                    $cardinfo['begin_timestamp'] = time() + 1800;
                }
                $cardinfo['end_timestamp'] = $cardinfo['end_timestamp']-9000;
                $data['begin_timestamp'] = date('Y-m-d H:i:s',$cardinfo['begin_timestamp']);
                $data['end_timestamp'] = date('Y-m-d H:i:s',$cardinfo['end_timestamp']);
            }else{
                $data['code'] = 9001;
                $data['msg'] = 'error';
            }
            return json($data);
        }

    }

    //获取常用链接
    public function getusedlink(){
        if (Request()->isAjax()){
            $map['top_mid'] = Session::get('login_top_mid');
            $CardMember = new CardMember();
            $card_id = $CardMember->where($map)->value('card_id');
            $Platurl = new Platurl();
            $agent_url = $Platurl->getagenturl('card_id', $card_id);

//            $card[0]['card_id'] = $card_id;

            $card[0]['url'] = $agent_url . '/mobile.php?s=/cardmarke/cardshare/card_id/' . $card_id;     //分享
            $card[0]['name'] = '[分享会员卡]';
            $card[1]['url'] = $agent_url . '/mobile.php?s=/carduser/opencard/card_id/' . $card_id;     //打开卡
            $card[1]['name'] = '[我的会员卡]';
            $card[2]['url'] = $agent_url . '/mobile.php?s=/carduser/recharge/card_id/' . $card_id;      //充值
            $card[2]['name'] ='[在线充值]';
            $card[3]['url'] = $agent_url . '/mobile.php?s=/carduser/index/card_id/' . $card_id;     //会员中心
            $card[3]['name'] = '[会员中心]';
            $card[4]['url'] = $agent_url . '/mobile.php?s=/carduser/balance/card_id/' . $card_id;     //余额
            $card[4]['name'] = '[我的余额]';
            $card[5]['url'] = $agent_url . '/mobile.php?s=/cardshop/goods/card_id/' . $card_id;     //积分商城
            $card[5]['name'] = '[积分商城]';
            if ($card){
                $res['code'] = 0;
                $res['message'] = 'success';
                $res['data']['item'] = $card;
            }else{
                $res['code'] = 0;
                $res['message'] = 'success';
                $res['data']['item'] = '';
            }
            return json($res);
        }
    }

    //获取常用事件
    public function getusedevent(){
        if (Request()->isAjax()){
            $CardClickput = new CardClickReplyPut();
            $map['top_mid'] = Session::get('login_top_mid');
            $list = $CardClickput->where($map)->field('click_key,title')->select();
            if ($list){
                $res['code'] = 0;
                $res['message'] = 'success';
                $res['data']['item'] = $list;
            }else{
                $res['code'] = 0;
                $res['message'] = 'success';
                $res['data']['item'] = '';
            }
            return json($res);
        }
    }

    //支付后送券
    public function paymentputcardslist(){
        $map['top_mid'] = Session::get('login_top_mid');
        $PaymentCardPut = new PaymentCardPut();
        $list = $PaymentCardPut->where($map)->select();
        $map['statu'] =1;
        $info['num'] =  $PaymentCardPut->where($map)->count();
        if (request()->isAjax()) {
            if ($info['num'] == 3) {
                $resa = ['code'=>9002,'message'=>'您的已生效规则已达到3条，添加失败！'];
            }else {
                $arr = request()->post();
                $data = $arr;
                $data['top_mid'] = Session::get('login_top_mid');
                if ($data['time_type'] == 'lasting') {
                    $data['start_time'] = strtotime(date('Y-m-d h:i:s', time()));
                    $data['end_time'] = strtotime(date('Y-m-d h:i:s', strtotime("+10 year")));
                    $data['times'] = date('Y-m-d h:i:s', $data['start_time']) . '  -  ' . date('Y-m-d h:i:s', $data['end_time']);
                } else {
                    $times = explode(" - ", $data['times']);
                    $data['start_time'] = strtotime($times[0]);
                    $data['end_time'] = strtotime($times[1]);
                }
                $cardlist = $this->card_zs_list($arr['cardlist']);
                $data['zs_no'] = count($cardlist);
                $data['zs_card_id_all'] = json_encode($cardlist, JSON_UNESCAPED_UNICODE);
                $data['zs_card_info'] = getgivecardnewnoz($data['zs_card_id_all'], 0);
                $data['statu'] = 1;
                $data['create_time'] = time();
                $PaymentCardPut = new PaymentCardPut();
                $res = $PaymentCardPut->allowField(true)->save($data);
                if ($res) {
                    $resa = ['code' => 0, 'message' => 'success'];
                } else {
                    $resa = ['code' => 9001, 'message' => 'error'];
                }
            }
            return json($resa);
        }
        $this->assign('info',$info);
        $this->assign('list', $list);
        return $this->fetch();
    }
    

    //支付后送券删除
    public function paymentputcardsdel()
    {
        $param = request()->param();
        if (isset($param['id'])) {
            $map['id'] = $param['id'];
            $map['top_mid'] = Session::get('login_top_mid');

            $PaymentCardPut = new PaymentCardPut();
            $res = $PaymentCardPut->where($map)->delete();
            if ($res) {
                $this->success('删除成功！', url('marke/paymentputcardslist'));
            } else {
                $this->error('删除失败！', url('marke/paymentputcardslist'));
            }

        }
    }


    //支付后送券状态
    public function paymentputcardsstatu()
    {

        if (Request()->isAjax()) {
            $PaymentCardPut = new PaymentCardPut();
            $mab['top_mid'] = Session::get('login_top_mid');
            $mab['statu'] = 1;
            $info['num'] = $PaymentCardPut->where($mab)->count();
            $param = request()->post();
            if (isset($param['id'])) {
                $map['id'] = $param['id'];
                $map['top_mid'] = Session::get('login_top_mid');
                $payment = $PaymentCardPut->where($map)->find();
                $data['statu'] = $payment['statu'] == 1 ? 0 : 1;
                if ($info['num'] == 3 && $data['statu'] == 1) {
                    $rarr['code'] = 9002;
                    $rarr['message'] = '您的已生效规则已达到3条，上架失败！';
                }else {
                    $res = $PaymentCardPut->save($data, $map);
                    if ($res) {
                        $rarr['code'] = 0;
                        $rarr['message'] = 'success';
                    } else {
                        $rarr['code'] = 9001;
                        $rarr['message'] = 'error';
                    }

                }
            }else{
                $rarr['code'] = 9003;
                $rarr['message'] = '非法操作';
            }
            return json($rarr);
        }
    }

    public function birthdaycare(Request $request){
        $CardBirthdayCare = new CardBirthdayCare();
        if ($request->isAjax()){
            $param = $request->post();
            $data = $param;
            if ($param['time_type'] == 'lasting' || $param['time_type'] == ""){
                $data['start_time'] = date('Y-m-d h:i:s',time());
                $data['end_time'] = date('Y-m-d h:i:s',strtotime("+10 year"));
                $data['times'] =  $data['start_time'] . " - ". $data['end_time'];
                $data['time_type'] = 'lasting';
            }else{
                $times = explode(" - ", $param['times']);
                $data['start_time'] = $times[0];
                $data['end_time'] = $times[1];
            }
            //END
            $cardlist = $this->card_zs_list($param['cardlist']);
            $data['zs_card_id_all'] = json_encode($cardlist,JSON_UNESCAPED_UNICODE);
            $data['zs_card_info'] = getgivecardnewnoz($data['zs_card_id_all'],0);
            //END
            $maps['top_mid'] = Session::get('login_top_mid');

            $info = $CardBirthdayCare->where($maps)->find();
            if ($info){
                $data['update_time'] = time();
                $res = $CardBirthdayCare->allowField(true)->save($data, $maps);
            }else {
                $Momerchant = new Momerchant();
                $data['wx_open_id'] = $Momerchant->where(['id'=>$maps['top_mid']])->value('wx_open_id');
                $data['top_mid'] = Session::get('login_top_mid');
                $data['create_time'] = time();
                $data['statu'] = 2;
                $res = $CardBirthdayCare->allowField(true)->save($data);
            }
            if ($res) {
                $rarr['code'] = 0;
                $rarr['message'] = '提交成功';
            } else {
                $rarr['code'] = 9001;
                $rarr['message'] = '提交失败';
            }
            return json($rarr);
        }else {
            $map['card_id'] = $this->get_cardus_id();
            $CardRank = new CardRank();
            $list = $CardRank->where($map)->select();
            $maps['top_mid'] = Session::get('login_top_mid');
            $info = $CardBirthdayCare->where($maps)->find();

            $carelist = $CardBirthdayCare->where($maps)->select();
            $this->assign('carelist', $carelist);
            $this->assign('info',$info);
            $this->assign('ranklist', $list);
            return $this->fetch();
        }
    }

    public function getsrcarecardslist(Request $request){
        if ($request->isAjax()) {
            $param = $request->post();
            $CardGen = new CardGeneral();
            $CardBirthdayCare = new CardBirthdayCare();
            $info = $CardBirthdayCare->where(array('id' => $param['id']))->find();
            $zs_card_id_all = json_decode($info['zs_card_id_all'], true);
            $cardlist = [];
            foreach ($zs_card_id_all as $k=>$v){
                $cardinfo = $CardGen->where('card_id',$v['zs_card_id'])->field('get_limit,title')->find();
                $cardlist[$k]['title'] = $cardinfo['title'];
                $cardlist[$k]['card_id'] = $v['zs_card_id'];
                $cardlist[$k]['get_limit'] = $cardinfo['get_limit'];
                $cardlist[$k]['zs_no'] = $v['zs_no'];
            }
            return json($cardlist);
        }
    }

    public function srcarestatu(Request $request){
        if ($request->isAjax()) {
            $param = $request->post();
            $CardBirthdayCare = new CardBirthdayCare();
            $map['id'] = $param['id'];
            $info = $CardBirthdayCare->where(array('id' => $param['id']))->find();
            $data['statu'] = $info['statu'] == 1 ? 2 : 1;
            $res = $CardBirthdayCare->save($data,$map);
            if ($res){
                $resa = ['code'=>0,'message'=>'保存成功'];
            }else{
                $resa = ['code'=>9001,'message'=>'保存失败'];
            }
            return json($resa);
        }
    }

    /*
     *
     * 商户优惠券
     *
     *
     */
    public function machputcards(){
        $map['top_mid'] = Session::get('login_top_mid');
        $map['is_pay'] = 0;
        $map['is_cgive'] = 0;
        $map['is_put'] = 1;
        $map['end_timestamp'] = ['GT',time()];
        $CardGeneral = new CardGeneral();
        $list = $CardGeneral->where($map)->order('is_mach desc')->paginate(10);
        $this->assign('list',$list);
        return $this->fetch();
    }

    public function machputcardsup(){
        $CardGeneral = new CardGeneral();
        $card_id = request()->param('card_id');
        $map['card_id'] = $card_id;
        $map['top_mid'] = Session::get('login_top_mid');
        $is_mach = $CardGeneral->where($map)->value('is_mach');
        $data['is_mach'] = $is_mach == 1?0:1;
        $res = $CardGeneral->save($data,$map);
        if ($res){
            $this->redirect('marke/machputcards');
        }else{
            $this->error('操作失败','marke/machputcards');
        }
    }



//        //群发卡券   原生消息版
//    public function massCard(){
//  //      $mid = request()->get('mid');
//        if (Request()->isPost()) {
//            $arr = request()->post();
//            $options = $this->option();
//            $weObj = new Wxobjopen($options);
//            if ($arr['type'] == 1){
//                //指定发放
//          //      $arr['type'] = true;
//                return json($arr);
//                $data = $this->getsend($arr);
//                return json($data);
//                $res = $weObj->mesgSend($data);
//            }else{
//                //分组发放
//                $arr['type'] = false;
//                $data = $this->getsendall($arr);
//                return json($data);
//                $res = $weObj->mesgSendAll($data);
//            }
//            if ($res['errcode'] == 0){
//                $data['creattime'] = time();
//                $CardPutRule = new CardPutRule();
//                $res = $CardPutRule->save($data);
//                if ($res == false){
//                    echo "存入失败";
//                }else{
//                    echo "投放成功";
//                }
//            }else{
//                echo "创建失败";
//            }
//        }else{
//            $mid = $this->get_mer_mid();
//            $map['statu'] = 0;
//            $map['mid'] = ['in',$mid];
//            $mab['statu'] = 0;
//            $top_mid = Session::get('login_top_mid');
//            $mab['top_mid'] = ['in',$top_mid];
//            $CardPutRule = new CardPutRule();
//            $CardGeneral = new CardGeneral();
//            $CardMember = new CardMember();
//            $CardUserGet = new CardUserGet();
//            $cards = $CardGeneral->where($mab)->select();
//  //          var_dump($cards);
//            $cardus = $CardMember->where($map)->select();
//            $cardu = $CardPutRule->where($map)->select();
//            $user = $CardUserGet->where(['card_type'=>'MEMBER_CARD'])->select();
//            $this->assign('cardus', $cardus);
//            $this->assign('cardu', $cardu);
//            $this->assign('cards', $cards);
//            $this->assign('user', $user);
//            return $this->fetch();
//        }
//    }
////
//    //分组发送
//    public function getSendall($arr){
//        $data['filter']['is_to_all'] = true;
//        if ($arr['type'] == 2){
//            $data['filter']['tag_id'] = $arr['touser'];
//        }
//        $data['msgtype'] = 'wxcard';
//        $data['wxcard'] = ['card_id'=>$arr['card_id']];
//        return $data;
//    }
//
//    //指定会员发布
//    public function getsend($arr){
//        $data = [
//            'touser'=>[
//                $arr['openid']
//            ],
//            'msgtype'=>'wxcard',
//            'wxcard'=>[ 'card_id'=>$arr['card_id']  ],
//        ];
//        return $data;
//    }

}
